import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:device_info_plus/device_info_plus.dart';

class BlePeripheralService {
  // 定义固定的 UUID，使用小写的 128 位 UUID 格式
  static const String SERVICE_UUID = "0000ffe0-0000-1000-8000-00805f9b34fb";
  static const String CONTROL_CHARACTERISTIC_UUID = "0000ffe1-0000-1000-8000-00805f9b34fb";
  static const String NOTIFY_CHARACTERISTIC_UUID = "0000ffe2-0000-1000-8000-00805f9b34fb";

  final DeviceInfoPlugin _deviceInfo = DeviceInfoPlugin();
  bool _isAdvertising = false;
  StreamController<String>? _commandController;
  Function(String)? onVideoNameGenerated;
  Function(bool)? onAdvertisingStateChanged;
  
  static const MethodChannel _channel = MethodChannel('blue_record/ble_peripheral');
  static const EventChannel _eventChannel = EventChannel('blue_record/ble_peripheral_events');
  StreamSubscription? _eventSubscription;

  // 初始化
  Future<void> initialize() async {
    _commandController = StreamController<String>.broadcast();
    
    try {
      // 输出详细的设备信息
      if (Platform.isAndroid) {
        final androidInfo = await _deviceInfo.androidInfo;
        debugPrint('设备信息:');
        debugPrint('- 制造商: ${androidInfo.manufacturer}');
        debugPrint('- 型号: ${androidInfo.model}');
        debugPrint('- Android版本: ${androidInfo.version.release}');
        debugPrint('- SDK版本: ${androidInfo.version.sdkInt}');
      }

      // 检查蓝牙权限
      await _checkPermissions();

      // 监听来自原生层的命令
      _eventSubscription = _eventChannel.receiveBroadcastStream().listen(
        (dynamic command) {
          if (command is String) {
            handleCommand(command);
          }
        },
        onError: (error) {
          debugPrint('事件流错误: $error');
        },
      );

    } catch (e) {
      debugPrint('BLE 初始化错误: $e');
      rethrow;
    }
  }

  Future<void> _checkPermissions() async {
    if (Platform.isAndroid) {
      var status = await Permission.bluetoothAdvertise.status;
      if (!status.isGranted) {
        status = await Permission.bluetoothAdvertise.request();
        if (!status.isGranted) {
          throw Exception('需要蓝牙广播权限');
        }
      }

      status = await Permission.bluetoothConnect.status;
      if (!status.isGranted) {
        status = await Permission.bluetoothConnect.request();
        if (!status.isGranted) {
          throw Exception('需要蓝牙连接权限');
        }
      }

      status = await Permission.bluetoothScan.status;
      if (!status.isGranted) {
        status = await Permission.bluetoothScan.request();
        if (!status.isGranted) {
          throw Exception('需要蓝牙扫描权限');
        }
      }
    }
  }

  // 开始广播
  Future<void> startAdvertising() async {
    if (_isAdvertising) return;

    try {
      await _channel.invokeMethod('startAdvertising');
      _isAdvertising = true;
      onAdvertisingStateChanged?.call(true);
      debugPrint('BLE 广播已启动');
    } catch (e) {
      debugPrint('启动广播错误: $e');
      rethrow;
    }
  }

  // 停止广播
  Future<void> stopAdvertising() async {
    if (!_isAdvertising) return;

    try {
      await _channel.invokeMethod('stopAdvertising');
      _isAdvertising = false;
      onAdvertisingStateChanged?.call(false);
      debugPrint('BLE 广播已停止');
    } catch (e) {
      debugPrint('停止广播错误: $e');
      rethrow;
    }
  }

  // 处理接收到的命令
  void handleCommand(String command) {
    debugPrint('处理命令: $command');
    _commandController?.add(command);
  }

  // 发送视频名称通知
  void sendVideoName(String videoName) {
    debugPrint('发送视频名称: $videoName');
    if (_isAdvertising) {
      _channel.invokeMethod('sendNotification', {'message': videoName});
    }
    handleCommand('VIDEO_NAME:$videoName');
  }

  // 获取命令流
  Stream<String> get commandStream => _commandController!.stream;

  // 检查是否正在广播
  bool get isAdvertising => _isAdvertising;

  // 释放资源
  void dispose() {
    stopAdvertising();
    _eventSubscription?.cancel();
    _commandController?.close();
    _commandController = null;
  }

  // 获取短 UUID（用于显示）
  static String getShortUUID(String uuid) {
    return uuid.substring(4, 8);
  }
} 